<template>
  <div>
    <el-dialog
      :title="tableList.title"
      :visible.sync="visible"
      width="60%"
      :before-close="handleClose"
    >
      <div>
        <div id="timePicter">
          <p style="text-align: left">
            <span class="demonstration">
              学校名称：
              <el-input
                placeholder="请输入学校名称"
                v-model="formData.schoolName"
                style="width: 300px; height: 40px"
                clearable
              >
              </el-input>
            </span>

            <span style="margin-left: 50px">
              <el-button
                @click="resetForm()"
                style="
                  background-color: #e6effa;
                  color: #126bff;
                  margin-left: 10px;
                  height: 36px;
                  width: 78px;
                  border-radius: 6px;
                  opacity: 1;
                  font-size: 14px;
                  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
                  font-weight: 400;
                  border: none;
                "
                >重置</el-button
              >
              <el-button
                type="primary"
                @click="submitForm(formData)"
                style="
                  height: 36px;
                  width: 78px;
                  background-color: #126bff;
                  border-radius: 6px;
                  opacity: 1;
                  color: #ffffff;
                  font-size: 14px;
                  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
                  font-weight: 400;
                  margin-left: 10px;
                  border: none;
                "
                >查询</el-button
              >
            </span>
          </p>
          <p style="text-align: left">
            <el-button
              class="btn"
              icon="iconfont icon-upload-copy"
              @click="exportExcel"
              >全部导出</el-button
            >
          </p>
        </div>

        <div>
          <el-table
            :data="dataList.res"
            border
            style="width: 100%"
            v-if="tableList.type == 0"
            v-loading="loading"
            element-loading-text="拼命加载中"
          >
            <el-table-column prop="id" label="序号" width="100">
              <!-- <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template> -->
              <template slot-scope="scope">
                {{ scope.$index + 1 + (currentPage - 1) * pageSize }}
              </template>
            </el-table-column>
            <el-table-column prop="dwmc" label="学校名称"> </el-table-column>
            <el-table-column prop="dwlx" label="单位类型"> </el-table-column>
            <el-table-column prop="huxuegang" label="护学岗人员数量">
            </el-table-column>
            <el-table-column prop="sign_numbers" label="打卡人数">
            </el-table-column>
            <el-table-column prop="sjdz" label="实际办公地点">
            </el-table-column>
            <el-table-column prop="fddbrxm" label="法人代表姓名">
            </el-table-column>
            <el-table-column prop="create_time" label="时间"> </el-table-column>
          </el-table>
          <el-table
            :data="dataList.res"
            style="width: 100%"
            border
            v-loading="loading"
            v-if="tableList.type == 1"
          >
            <el-table-column prop="id" label="序号" width="100">
              <template slot-scope="scope">
                {{ scope.$index + 1 + (currentPage - 1) * pageSize }}
              </template>
              <!-- <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template> -->
            </el-table-column>
            <el-table-column prop="dwmc" label="护卫学校名称">
            </el-table-column>
            <el-table-column prop="photo" label="照片">
              <template v-slot:default="scope">
                <el-image
                  style="
                    width: 50px;
                    height: 50px;
                    padding: 5px;
                    box-sizing: border-box;
                  "
                  :src="scope.row.photo"
                  v-if="scope.row.photo"
                  :preview-src-list="[scope.row.photo]"
                >
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="photo" label="抓拍图片">
              <template v-slot:default="scope">
                <el-image
                  style="
                    width: 50px;
                    height: 50px;
                    padding: 5px;
                    box-sizing: border-box;
                  "
                  :src="scope.row.photo"
                  v-if="scope.row.photo"
                  :preview-src-list="[scope.row.photo]"
                >
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="xm" label="姓名"> </el-table-column>
            <el-table-column prop="now_count" label="当前打卡次数">
            </el-table-column>
            <el-table-column prop="address" label="打卡地点"> </el-table-column>
            <el-table-column prop="create_time" label="打卡时间">
            </el-table-column>
          </el-table>

          <el-table
            :data="dataList.res"
            border
            style="width: 100%"
            v-if="tableList.type == 2"
            v-loading="loading"
            element-loading-text="拼命加载中"
          >
            <el-table-column prop="id" label="序号" width="100">
              <template slot-scope="scope">
                {{ scope.$index + 1 + (currentPage - 1) * pageSize }}
              </template>
            </el-table-column>
            <el-table-column prop="dwmc" label="学校名称"> </el-table-column>
            <el-table-column prop="dwlx" label="单位类型"> </el-table-column>
            <el-table-column prop="xzqydm" label="所属行政区域">
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100, 150, 200]"
            :page-size="pageSize"
            layout="total, prev, pager, next, sizes"
            :total="dataList.count"
            style="float: right; margin-top: 20px"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :title="
        tableList.title == '学校总打卡数量' ||
        tableList.title == '学校未打卡总数' ||
        tableList.title == '今日学校打卡总数' ||
        tableList.title == '今日未打卡学校总数'
          ? '导出条数'
          : '数据导出'
      "
      :visible.sync="importVisible"
      :before-close="handleCloseImportant"
      width="35%"
      top="0"
      id="import"
    >
      <p>
        <span
          style="margin-left: 10px; text-align: center"
          v-if="
            tableList.title == '学校总打卡数量' ||
            tableList.title == '学校未打卡总数' ||
            tableList.title == '今日学校打卡总数' ||
            tableList.title == '今日未打卡学校总数'
          "
        >
          <span
            style="margin-top: 10px; display: inline-block; text-align: left"
          >
            请选择每页条数：

            <el-select
              v-model="formData.pagesize"
              placeholder="请选择"
              style="width: 300px"
              @change="change"
            >
              <el-option
                v-for="item in optionsPagesize"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </span>
          <br />
          <span
            style="margin-top: 10px; display: inline-block; margin-left: 18px"
          >
            请选择页码：
            <el-select
              v-model="formData.page"
              placeholder="请选择"
              style="width: 300px; padding-left: 18px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </span>
        </span>
        <span
          class="demonstration"
          style="margin-left: 10px"
          v-if="
            tableList.title == '今日总打卡人数' ||
            tableList.title == '今日总打卡次数'
          "
          >时间：
          <el-date-picker
            v-model="formData.times"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 80%"
          >
          </el-date-picker>
        </span>
      </p>
      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          @click="handleCloseImportant"
          style="
            background-color: #e6effa;
            color: #126bff;
            margin-left: 10px;
            height: 36px;
            width: 78px;
            border-radius: 6px;
            opacity: 1;
            font-size: 14px;
            font-family: Microsoft YaHei-Regular, Microsoft YaHei;
            font-weight: 400;
            border: none;
          "
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="confirmImport"
          style="
            height: 36px;
            width: 78px;
            background-color: #126bff;
            border-radius: 6px;
            opacity: 1;
            color: #ffffff;
            font-size: 14px;
            font-family: Microsoft YaHei-Regular, Microsoft YaHei;
            font-weight: 400;
            margin-left: 10px;
            border: none;
          "
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="系统提示"
      :visible.sync="alert"
      :before-close="handleCloseImportant"
      width="20%"
      top="0"
      id="import"
    >
      <p>导出超时，请重新导出！</p>
      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          @click="alert = false"
          style="
            background-color: #e6effa;
            color: #126bff;
            margin-left: 10px;
            height: 36px;
            width: 78px;
            border-radius: 6px;
            opacity: 1;
            font-size: 14px;
            font-family: Microsoft YaHei-Regular, Microsoft YaHei;
            font-weight: 400;
            border: none;
          "
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="alert = false"
          style="
            height: 36px;
            width: 78px;
            background-color: #126bff;
            border-radius: 6px;
            opacity: 1;
            color: #ffffff;
            font-size: 14px;
            font-family: Microsoft YaHei-Regular, Microsoft YaHei;
            font-weight: 400;
            margin-left: 10px;
            border: none;
          "
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  allSignsUsersExcel,
  todaySignsNumberExcel,
  todaySignNumbersExcel,
  allSignsUnUsersExcel,
  jrdwkSchool,
} from "@/api/mx";
// import { saveAs } from "file-saver";
import * as XLSX from "xlsx/xlsx.mjs";
// function initExcel() {
//   const arr = [];
//   // {{ this.dataList.count / this.dataList.pages }}
//   // {{ this.dataList.pages }}
//   for (
//     let i = 0;
//     i < parseInt(this.dataList.count / this.dataList.pages);
//     i++
//   ) {
//     arr.push({
//       value: i++,
//       label: i++,
//     });
//   }
//   return 111;
// }
// initExcel();
export default {
  name: "APP",
  components: {},
  data() {
    return {
      tableData: [],
      tablePeopleData: [],
      importVisible: false,
      alert: false,
      options: [
        {
          value: 1,
          label: "1",
        },
        {
          value: 2,
          label: "2",
        },
        {
          value: 3,
          label: "3",
        },
        {
          value: 4,
          label: "4",
        },
      ],
      optionsPagesize: [
        {
          value: 20,
          label: "20",
        },
        {
          value: 50,
          label: "50",
        },
        {
          value: 100,
          label: "100",
        },
        {
          value: 150,
          label: "150",
        },
        {
          value: 200,
          label: "200",
        },
      ],
      // options: initExcel(),
      value2: "",
      pamas: {
        dwmc: "",
        begin: "",
        token: JSON.parse(localStorage.getItem("userInfo")).token,
      },
      // formData: {
      //   schoolName: "",
      //   times: "",
      // },
    };
  },

  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    tableList: {
      type: Object,
      default: null,
    },
    dataList: {
      type: Object,
      default: null,
    },
    currentPage: {
      type: Number,
      default: 1,
    },
    pageSize: {
      type: Number,
      default: 50,
    },
    formData: {
      type: Object,
      default: null,
    },
    loading: {
      type: Boolean,
      default: true,
    },
  },
  // beforeMount(){},
  mounted() {
    console.log(this.dataList);
  },
  beforeMount() {},
  computed: {},
  methods: {
    change(e) {
      console.log(e);
      console.log(Math.ceil(this.dataList.count / e));
      let arr = [];
      for (let i = 1; i <= Math.ceil(this.dataList.count / e); i++) {
        if (i == 0 || i == 1) {
          i = 1;
        }
        arr.push({
          value: i,
          label: i,
        });
      }
      this.options = arr;
    },
    // 取消导出
    handleCloseImportant() {
      console.log("22222222");
      this.$emit("handleCloseImportant");
      this.importVisible = false;
      this.resetForm();
    },
    // 确认导出
    confirmImport() {
      const headers = [
        "id",
        "学校名称",
        "单位类型",
        "实际办公地点",
        "法人代表姓名",
        "护学岗人员数量",
        "打卡人数",
        "时间",
      ];
      const headers2 = [
        "id",
        "护卫学校名称",
        "姓名",
        "当前打卡次数",
        "打卡地址",
        "打卡时间",
      ];
      const headers4 = [
        "id",
        "护卫学校名称",
        "所属区域",
        "单位类型",
        "所属派出所",
      ];
      const headers3 = [
        "id",
        "所属区域",
        "所属派出所",
        "学校名称",
        "单位类型",
        "护学岗人员数量",
        "打卡人数",
        "实际办公地点",
        "法人代表姓名",
        "时间",
      ];
      this.$emit("loadings", true);
      // return;
      this.$notify.info({
        title: "下载中",
        message: "数据下载中,请稍作等待",
      });
      if (
        this.tableList.title == "今日总打卡人数" ||
        this.tableList.title == "今日总打卡次数" ||
        this.tableList.title == "今日学校打卡总数"
      ) {
        if (this.tableList.title == "今日学校打卡总数") {
          this.pamas.pagesize = this.formData.pagesize;
          this.pamas.page = this.formData.page;
          delete this.pamas.begin;
          delete this.pamas.end;

          console.log(this.pamas);
          todaySignsNumberExcel(this.pamas)
            .then((res) => {
              if (res.code == 200) {
                res.data.forEach((item) => {
                  item.create_time = this.$moment(
                    item.create_time * 1000
                  ).format("YYYY-MM-DD HH:mm:ss");
                });

                // console.log(res.da);
                this.export(res.data, headers3);
              } else {
                this.$message({
                  message: res.message,
                  type: "error",
                });
              }
              this.$emit("loadingClose", false);
            })
            .catch((err) => {
              console.log(err);
              this.alert = true;
              this.$emit("loadingClose", false);
            });
        } else if (
          this.tableList.title == "今日总打卡次数" ||
          this.tableList.title == "今日总打卡人数"
        ) {
          delete this.pamas.pagesize;
          // this.$emit("loading");
          console.log(this.formData);
          console.log(this.pamas);

          if (this.formData.times == [] || this.formData.times == null) {
            this.pamas.end = "";
            this.pamas.begin = "";
          } else {
            this.pamas.begin = this.formData.times[0];
            this.pamas.end = this.formData.times[1];
          }
          // this.pamas.xzqydm = "大城县";
          todaySignNumbersExcel(this.pamas)
            .then((res) => {
              if (res.code == 200) {
                res.data.forEach((item) => {
                  item.create_time = this.$moment(
                    item.create_time * 1000
                  ).format("YYYY-MM-DD HH:mm:ss");
                });
                this.export(res.data, headers2);
              } else if (res.code == 400) {
                this.$message({
                  message: "查询时间段信息有误",
                  type: "error",
                });
              } else {
                this.$message({
                  message: res.message,
                  type: "error",
                });
              }
              this.$emit("loadingClose", false);
            })
            .catch((err) => {
              console.log(err);
              this.alert = true;
              this.$emit("loadingClose", false);
            });
        } else {
          return;
        }
      } else if (this.tableList.title == "学校总打卡数量") {
        this.pamas.pagesize = this.formData.pagesize;
        this.pamas.page = this.formData.page;
        this.pamas.dwmc = this.formData.schoolName;
        delete this.pamas.begin;
        delete this.pamas.end;
        console.log(this.pamas);

        // console.log("学校总打卡数量");
        allSignsUsersExcel(this.pamas)
          .then((res) => {
            // console.log(res);
            if (res.code == 200) {
              res.data.forEach((item) => {
                item.create_time = this.$moment(item.create_time * 1000).format(
                  "YYYY-MM-DD HH:mm:ss"
                );
              });
              this.export(res.data, headers3);
            } else {
              this.$message({
                message: res.message,
                type: "error",
              });
            }
            this.$emit("loadingClose", false);
          })
          .catch((err) => {
            console.log(err);
            this.alert = true;
            this.$emit("loadingClose", false);
          });
      } else if (this.tableList.title == "学校未打卡总数") {
        delete this.pamas.begin;
        delete this.pamas.end;

        this.pamas.pagesize = this.formData.pagesize;
        this.pamas.page = this.formData.page;
        console.log(this.pamas);

        // // console.log("学校未打卡总数");
        allSignsUnUsersExcel(this.pamas)
          .then((res) => {
            // console.log(res);
            if (res.code == 200) {
              res.data.forEach((item) => {
                item.create_time = this.$moment(item.create_time * 1000).format(
                  "YYYY-MM-DD HH:mm:ss"
                );
              });
              this.export(res.data, headers3);
            } else {
              this.$message({
                message: res.message,
                type: "error",
              });
            }
            this.$emit("loadingClose", false);
          })
          .catch((err) => {
            console.log(err);
            this.alert = true;
            this.$emit("loadingClose", false);
          });
      } else if (this.tableList.title == "今日未打卡学校总数") {
        console.log("今日未打卡学校总数");
        console.log("--------------");
        delete this.pamas.begin;
        delete this.pamas.end;
        this.pamas.pagesize = this.formData.pagesize;
        this.pamas.page = this.formData.page;
        console.log(this.pamas);
        // // console.log("学校未打卡总数");
        jrdwkSchool(this.pamas)
          .then((res) => {
            // console.log(res);
            if (res.code == 200) {
              this.export(res.data.res, headers4);
            } else {
              this.$message({
                message: res.message,
                type: "error",
              });
            }
            this.$emit("loadingClose", false);
          })
          .catch((err) => {
            console.log(err);

            this.$emit("loadingClose", false);
          });
      }
      this.importVisible = false;
      console.log(this.pamas);
    },
    // 关闭弹窗
    handleClose() {
      // this.formData.schoolName = "";
      this.pamas = {
        dwmc: "",
        begin: "",
        end: "",
        token: JSON.parse(localStorage.getItem("userInfo")).token,
      };
      this.$emit("handel", {
        title: this.tableList.title,
        show: false,
      });
    },
    // 搜索
    submitForm(e) {
      console.log(e);
      let that = this;
      that.pamas.dwmc = e.schoolName;
      console.log(that.pamas);
      this.$emit("searchName", {
        title: that.tableList.title,
        pamas: that.pamas,
      });
    },
    // 搜索条件重置
    resetForm() {
      this.pamas = {
        dwmc: "",
        begin: "",
        end: "",
        token: JSON.parse(localStorage.getItem("userInfo")).token,
      };
      this.$emit("resetList", {
        title: this.tableList.title,
        schoolName: this.pamas,
      });
      this.$emit("loadingClose", false);
    },
    // 导出数据
    // 导出数据
    exportExcel() {
      console.log("导出数据");
      console.log(this.tableList.title);
      console.log(this.pamas);
      delete this.pamas.page;
      this.importVisible = true;
    },
    // 导出Excel
    export(data, headers) {
      // console.log(data);
      // console.log(headers);
      // ====================
      this.$message({
        message: "导出成功",
        type: "sucess",
      });
      const workbook = XLSX.utils.book_new();

      // 创建一个新的工作表
      const worksheet = XLSX.utils.aoa_to_sheet([]);

      // 将表头添加到工作表中
      XLSX.utils.sheet_add_aoa(worksheet, [headers], { origin: "A1" });

      // 根据表头的位置调整数据的位置
      const startRow = 1; // 数据开始的行号
      const startCol = 0; // 数据开始的列号
      // 需要在则合理判断data 是
      const dataRows = data.map((item, index) => {
        const rowData = [];
        console.log(headers);
        if (headers[2] == "姓名") {
          rowData[startCol] = item.ywlsh; // 业务流水号
          rowData[startCol + 1] = item.dwmc; // 护卫学校名称
          rowData[startCol + 2] = item.xm; // 姓名
          rowData[startCol + 3] = item.now_count; // 当前打卡次数
          rowData[startCol + 4] = item.address; // 打卡地点
          rowData[startCol + 5] = item.create_time; // 打卡时间
          return rowData;
        } else if (headers[2] == "所属派出所") {
          rowData[startCol] = item.ywlsh; // 业务流水号
          rowData[startCol + 1] = item.xzqydm; // 所属区域 department_name
          rowData[startCol + 2] = item.department_name; // 所属区域 department_name
          rowData[startCol + 3] = item.dwmc; // 单位名称
          rowData[startCol + 4] = item.dwlx; // 单位类型
          rowData[startCol + 5] = item.huxuegang; // 护学岗人数
          rowData[startCol + 6] = item.sign_numbers; // 打卡人数
          rowData[startCol + 7] = item.sjdz; // 实际办公地址
          rowData[startCol + 8] = item.fddbrxm; // 法定代表人姓名
          rowData[startCol + 9] = item.create_time; // 创建时间
          return rowData;
        } else if (headers[2] == "所属区域") {
          console.log(headers);
          rowData[startCol] = item.ywlsh; // 业务流水号
          rowData[startCol + 1] = item.dwmc; // 单位名称
          rowData[startCol + 2] = item.xzqydm; // 所属区域 department_name
          rowData[startCol + 3] = item.dwlx; // 单位类型
          rowData[startCol + 4] = item.department_name; //  department_name 所属派出所
          return rowData;
        }
      });
      XLSX.utils.sheet_add_aoa(worksheet, dataRows, {
        origin: { r: startRow, c: startCol },
        skipHeader: true,
      });

      // 将工作表添加到工作簿中
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

      // 导出文件
      XLSX.writeFile(workbook, this.tableList.title + ".xlsx");
      // XLSX.writeFile(
      //   workbook,
      //   this.pamas.begin + "-" + this.pamas.end + ".xlsx"
      // );
      this.$notify({
        title: "成功",
        message: "数据下载成功，请查收",
        type: "success",
      });
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      // this.pageSize = val;
      this.$emit("SizeChange", {
        val,
        title: this.tableList.title,
      });
    },
    //判断当前页是否是最后一页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);

      this.$emit("nextPage", {
        val,
        title: this.tableList.title,
      });
    },
  },
  created() {},
};
</script>
<style lang="scss" scoped>
/deep/.el-dialog {
  border-radius: 20px;
  overflow: auto;
  padding-bottom: 15px;
}
.btn {
  width: 108px;
  height: 36px;
  padding: 0;
  background: #126bff;
  border-radius: 6px;
  opacity: 1;
  vertical-align: middle;
  font-size: 16px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 400;
  color: #ffffff;
  margin: 10px 0 10px 0;
}
.demonstration {
  display: inline-block;
  margin-bottom: 10px;
}
/deep/.el-input__inner {
  border: 1px solid #d7dbe3 !important;
  background-color: white !important;
  border-radius: 6px !important;
}
/deep/.has-gutter tr th {
  color: black;
  text-align: center;
  background-color: #ecf5ff;
}
::v-deep.el-table {
  border: 1px #d7dbe3 solid;
  border-radius: 10px;
}
#import /deep/.el-dialog {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.el-dialog__title {
  width: 96px;
  height: 33px;
  font-size: 24px;
  font-weight: 400;
  color: #13213b;
  -webkit-text-fill-color: transparent;
}
</style>
